from binascii import b2a_hex
from Crypto.Cipher import AES
from tkinter import *
from tkinter import ttk
from tkinter.messagebox import showinfo


class MainUI(Tk):
    def __init__(self):
        super().__init__()
        self.w = 250
        self.h = 150
        self.center()
        self.title('license工具')
        self.mac = StringVar()
        self.date = StringVar()
        self.result = StringVar()
        self.create_btn = StringVar()
        self.setup_ui()
        self.aesKey = b'2024052020240520'  # 加密与解密所使用的密钥，长度必须是16的倍数
        self.aesIv = b'2024052020240520'  # initial Vector,长度要与aesKey一致
        self.aesMode = AES.MODE_CBC  # 使用CBC模式

    def center(self):
        ww = self.winfo_screenwidth()
        wh = self.winfo_screenheight()
        x = (ww - self.w) / 2
        y = (wh - self.h) / 2
        self.geometry('%dx%d+%d+%d' % (self.w, self.h, x, y))

    def setup_ui(self):
        Label(self, bg='pink').place_configure(x=0, y=0, width=250, height=150)
        Label(self, text='主机mac:', bg='pink').place_configure(x=20, y=30)
        ttk.Entry(self, textvariable=self.mac).place_configure(x=80, y=30)
        Label(self, text='有效日期:', bg='pink').place_configure(x=20, y=60)
        ttk.Entry(self, textvariable=self.date).place_configure(x=80, y=60)
        self.create_btn = ttk.Button(self, text='生成', command=self.create, )
        self.create_btn.place_configure(x=105, y=90)

    def encrypt(self, content):
        """ 将MAC地址和Date进行加密 """

        # 读取加密内容，并处理成16位的倍数
        while len(content) % 16:
            content += ' '
        content = content.encode('utf-8')

        # 对物理地址和license期限进行加密
        aes = AES.new(self.aesKey, self.aesMode, self.aesIv)
        encrypted_content = aes.encrypt(content)

        return (b2a_hex(encrypted_content))

    def gen_license_file(self, mac, license_time_limit):
        """ 生成license文件 """
        license_file = './License.dat'

        with open(license_file, 'w') as LF:
            LF.write('MAC : ' + mac + '\n')
            LF.write('Date : ' + license_time_limit + '\n')

            sign = self.encrypt(mac + '#' + license_time_limit)
            LF.write('Sign : ' + str(sign.decode('utf-8')) + '\n')
        return "生成license文件成功！"

    def create(self):
        # 生成license文件
        self.result = self.gen_license_file(self.mac.get(), self.date.get())
        showinfo('成功', self.result)


if __name__ == '__main__':
    m = MainUI()
    m.mainloop()
